
package com.joysuch.wwyt.mh.service.impl;

import com.joysuch.wwyt.api.mh.entity.MhPlatformPoint;
import com.joysuch.wwyt.api.mh.repository.MhPlatformPointDao;
import com.joysuch.wwyt.bp.bean.BpMonitoringPointBean;
import com.joysuch.wwyt.bp.entity.*;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.cache.AbstractRedisVersionCache;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.dataperm.annotation.EnableDataPermission;
import com.joysuch.wwyt.mh.bean.MhMonitoringPointBean;
import com.joysuch.wwyt.mh.bean.MhMonitoringPointListBean;
import com.joysuch.wwyt.mh.bean.MhMonitoringPointReqBean;
import com.joysuch.wwyt.mh.dto.MhMonitoringPointDto;
import com.joysuch.wwyt.mh.entity.MhAlarmMessage;
import com.joysuch.wwyt.mh.entity.MhMonitoringPoint;
import com.joysuch.wwyt.mh.entity.MhMonitoringType;
import com.joysuch.wwyt.mh.entity.dsl.QMhMonitoringPoint;
import com.joysuch.wwyt.mh.repository.MhAlarmMessageDao;
import com.joysuch.wwyt.mh.repository.MhMonitoringPointDao;
import com.joysuch.wwyt.mh.repository.MhMonitoringTypeDao;
import com.joysuch.wwyt.mh.service.MhMonitoringPointService;
import com.joysuch.wwyt.mh.service.MhMonitoringRealTimeService;
import com.joysuch.wwyt.mh.storage.IMonitorPointDataService;
import com.joysuch.wwyt.mh.storage.MonitorPointData;
import com.joysuch.wwyt.monitoringcenter.service.MonitoringCenterService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Transactional
public class MhMonitoringPointServiceImpl extends AbstractRedisVersionCache<MhMonitoringPoint>
        implements MhMonitoringPointService {

    @Autowired
    private MhMonitoringPointDao dao;
    @Autowired
    private MhMonitoringTypeDao mhMonitoringTypeDao;
    @Autowired
    private BpDeviceFacilityCollectionDao bpDeviceFacilityCollectionDao;
    @Autowired
    private IMonitorPointDataService monitorPointDataService;
    @Autowired
    private BpMonitoringPointRelDao bpMonitoringPointRelDao;
    @Autowired
    private BpDeviceFacilityMonitoringPointDao bpDeviceFacilityMonitoringPointDao;
    @Autowired
    private MhAlarmMessageDao mhAlarmMessageDao;
    @Autowired
    private MhPlatformPointDao mhPlatformPointDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BpProductionFacilityDao bpProductionFacilityDao;
    @Autowired
    private BpStorageTankAreaDao bpStorageTankAreaDao;
    @Autowired
    private BpStorageTankDao bpStorageTankDao;
    @Autowired
    private BpManufacturingTechDao bpManufacturingTechDao;
    @Autowired
    private BpStoreHouseDao bpStoreHouseDao;
    @Autowired
    private MhMonitoringRealTimeService mhMonitoringRealTimeService;
    @Autowired
    private MonitoringCenterService monitoringCenterService;


    @Override
    public void add(MhMonitoringPoint point) {
        Assert.isTrue(dao.countOfCode(point.getPointCode()) == 0, String.format("编号%s已经存在", point.getPointCode()));
        //阈值判断
        judgePointValue(point);
        MhMonitoringType type = mhMonitoringTypeDao.getOne(point.getMhMonitoringType().getId());
        point.setMhMonitoringType(type);
        point.setTenentId(Context.getCurrentTenantId());
        point.setOrgCode(Context.getCompanyCode());
        if (point.getState() == null) {
            point.setState(1);
        }
        point.setShowState(DataStateTypes.EFFECTIVE.getState());
        dao.save(point);
        changeTypeNumber(type);
    }

    /**
     * 报警阈值规则：低低 < 低 < 高 < 高高
     */
    public void judgePointValue(MhMonitoringPoint point) {
        Double highValue1 = null;
        Double highValue2 = null;
        Double lowValue1 = null;
        Double lowValue2 = null;
        if (StringUtils.isNotBlank(point.getHighValue1())) {
            highValue1 = Double.valueOf(point.getHighValue1());
        }
        if (StringUtils.isNotBlank(point.getHighValue2())) {
            highValue2 = Double.valueOf(point.getHighValue2());
        }
        if (StringUtils.isNotBlank(point.getLowValue1())) {
            lowValue1 = Double.valueOf(point.getLowValue1());
        }
        if (StringUtils.isNotBlank(point.getLowValue2())) {
            lowValue2 = Double.valueOf(point.getLowValue2());
        }

        int resultFlag = 0;
        //同低位
        if (lowValue1 != null && lowValue2 != null) {
            if (lowValue1 <= lowValue2) {
                resultFlag = 1;
            }
        }
        //同高位
        if (resultFlag == 0 && highValue1 != null && highValue2 != null) {
            if (highValue1 >= highValue2) {
                resultFlag = 1;
            }
        }
        //跨位
        if (resultFlag == 0 && lowValue1 != null) {
            if (highValue1 != null && lowValue1 >= highValue1) {
                resultFlag = 1;
            }
            if (resultFlag == 0 && highValue2 != null && lowValue1 >= highValue2) {
                resultFlag = 1;
            }
        }
        if (resultFlag == 0 && lowValue2 != null && lowValue1 == null) {
            if (highValue1 != null && lowValue2 >= highValue1) {
                resultFlag = 1;
            }
            if (resultFlag == 0 && highValue2 != null && lowValue2 >= highValue2) {
                resultFlag = 1;
            }
        }
        if (resultFlag == 1) {
            throw new IllegalArgumentException("请正确填写报警阈值");
        }
    }

    @Override
    public void edit(MhMonitoringPoint point) {
        Long id = point.getId();
        MhMonitoringPoint mhMonitoringPoint = dao.findById(id).get();
        Long tenentId = mhMonitoringPoint.getTenentId();
        String orgCode = mhMonitoringPoint.getOrgCode();
        Assert.isTrue(dao.countOfCodeExclude(point.getPointCode(), point.getId()) == 0,
                String.format("编号%s已经存在", point.getPointCode()));
        MhMonitoringType type = mhMonitoringTypeDao.findById(point.getMhMonitoringType().getId()).get();
        point.setDeleteFlag("0");
        point.setMhMonitoringType(type);
        if (point.getState() == null) {
            point.setState(1);
        }
        point.setOrgCode(orgCode);
        point.setTenentId(tenentId);
        delete(getKeyFromData(point));
        dao.save(point);
        changeTypeNumber(type);
    }

    @Override
    public Page<MhMonitoringPointListBean> list(Pageable pageable, String nameOrCode, String pointCode,
                                                Long monitoringTypeId, Long categoryId, Integer showFlag, Integer filter, Integer status) {
        pageable = PageDataUtils.addOrderByDesc(pageable, "id");
        QMhMonitoringPoint mmp = QMhMonitoringPoint.mhMonitoringPoint;
        Predicate predicate = mmp.isNotNull();

        predicate = nameOrCode == null ? predicate
                : ExpressionUtils.and(predicate,
                ExpressionUtils.or(mmp.name.like("%" + nameOrCode + "%"), mmp.pointCode.like("%" + nameOrCode + "%")));
        // predicate = pointCode == null ? predicate : ExpressionUtils.and(predicate, mmp.pointCode.like( "%" +name+ "%"
        // ));
        if (null != status && 0 == status) {
            predicate = ExpressionUtils.and(predicate, mmp.location.isNull());
        } else if (null != status && 1 == status) {
            predicate = ExpressionUtils.and(predicate, mmp.location.isNotNull());
        }

        predicate = ExpressionUtils.and(predicate,
                ExpressionUtils.or(mmp.showState.eq(DataStateTypes.EFFECTIVE.getState()), mmp.showState.isNull()));

        predicate = monitoringTypeId == null ? predicate
                : ExpressionUtils.and(predicate, mmp.mhMonitoringType.id.eq(monitoringTypeId));
        predicate = categoryId == null ? predicate
                : ExpressionUtils.and(predicate, mmp.mhMonitoringType.categoryId.eq(categoryId));
        //filter为1 过滤绑定过的监测点
        if (filter != null && filter.intValue() == 1) {
            List<Long> pointIds = bpMonitoringPointRelDao.getPointIdListAndRefTypeNotEq("manufacturing_tech");
            if (!CollectionUtils.isEmpty(pointIds)) {
                predicate = ExpressionUtils.and(predicate, mmp.id.notIn(pointIds));
            }
        }
        Page<MhMonitoringPoint> all = dao.findAll(predicate, pageable);
        List<MhMonitoringPointListBean> list = new ArrayList<>();
        if (!all.isEmpty()) {
            for (MhMonitoringPoint m : all) {
                list.add(this.getListBeanFromPoint(m, showFlag));
            }
        }
        return new PageImpl<>(list, pageable, all.getTotalElements());
    }

    @Override
    public Long getNumForHaveLocation(Integer flag) {
        QMhMonitoringPoint mmp = QMhMonitoringPoint.mhMonitoringPoint;
        Predicate predicate = mmp.isNotNull();
        predicate = ExpressionUtils.and(predicate,
                ExpressionUtils.or(mmp.showState.eq(DataStateTypes.EFFECTIVE.getState()), mmp.showState.isNull()));
        predicate = ExpressionUtils.and(predicate, mmp.mhMonitoringType.categoryId.eq(1L));
        if (null != flag && 1 == flag) {
            predicate = ExpressionUtils.and(predicate, mmp.location.isNotNull());
        }
        return dao.count(predicate);
    }

    @Override
    public Page<MhMonitoringPointListBean> page(Pageable pageable, String name, String pointCode,
                                                Long monitoringTypeId, Long categoryId) {
        pageable = PageDataUtils.addOrderByDesc(pageable, "id");
        QMhMonitoringPoint mmp = QMhMonitoringPoint.mhMonitoringPoint;
        Predicate predicate = mmp.isNotNull();

        predicate = name == null ? predicate
                : ExpressionUtils.and(predicate,
                ExpressionUtils.or(mmp.name.like("%" + name + "%"), mmp.pointCode.like("%" + name + "%")));
        // predicate = pointCode == null ? predicate : ExpressionUtils.and(predicate, mmp.pointCode.like( "%" +name+ "%"
        // ));
        predicate = monitoringTypeId == null ? predicate
                : ExpressionUtils.and(predicate, mmp.mhMonitoringType.id.eq(monitoringTypeId));

        predicate = categoryId == null ? predicate
                : ExpressionUtils.and(predicate, mmp.mhMonitoringType.categoryId.eq(categoryId));

        Page<MhMonitoringPoint> all = dao.findAll(predicate, pageable);
        List<MhMonitoringPointListBean> list = new ArrayList<>();
        if (!all.isEmpty()) {
            for (MhMonitoringPoint m : all) {
                this.getListBeanFromPoint(m, null);
            }
        }
        return new PageImpl<>(list, pageable, 0);
    }

    private MhMonitoringPointListBean getListBeanFromPoint(MhMonitoringPoint m, Integer showFlag) {
        MhMonitoringPointListBean bean = new MhMonitoringPointListBean();
        bean.setId(m.getId());
        bean.setName(m.getName());
        bean.setMonitoringTypeId(m.getMhMonitoringType().getId());
        bean.setLevel1Threshold(m.getLevel1Threshold());
        bean.setLevel2Threshold(m.getLevel2Threshold());
        bean.setMinitoringTypeName(m.getMhMonitoringType().getName());
        bean.setConnectState(querySensorState(m.getPointCode()));

        bean.setState(m.getState());
        if (showFlag == null || showFlag != 0) {
            if (m.getState() != null && m.getState() == 1) {
                if (m.getSwitchs() != null) {
                    if (m.getSwitchs().equals("1")) {
                        bean.setSwitchs("1");
                        bean.setSwitchsName("开");
                        bean.setRealtimeValue("1.0");
                        bean.setConnectStateName("已连接");
                        bean.setConnectState(1);
                    }
                    if (m.getSwitchs().equals("0")) {
                        bean.setSwitchsName("关");
                        bean.setSwitchs("0");
                        bean.setRealtimeValue("0.0");
                        bean.setConnectStateName("已连接");
                        bean.setConnectState(1);
                    }
                } else {
                    MonitorPointData realTimeValue = monitorPointDataService
                            .realTimeVal(Context.getCurrentTenantId(), Context.getCompanyCode(),
                                    m.getPointCode())
                            .orElse(null);
                    if (realTimeValue == null) {
                        bean.setConnectStateName("未连接");
                        bean.setConnectState(0);
                    } else {
                        bean.setConnectStateName("已连接");
                        bean.setRealtimeValue(realTimeValue.getValue().toString());
                        bean.setConnectState(1);
                    }
                }
            } else {
                bean.setConnectStateName("未连接");
                bean.setConnectState(0);
                if (m.getSwitchs() != null) {
                    bean.setSwitchsName("关");
                    bean.setSwitchs("0");
                    bean.setRealtimeValue("0.0");
                }
            }
        }
        bean.setPointCode(m.getPointCode());
        bean.setHighValue1(m.getHighValue1());
        bean.setHighValue2(m.getHighValue2());
        bean.setLowValue1(m.getLowValue1());
        bean.setLowValue2(m.getLowValue2());
        bean.setUnit(m.getUnit());
        bean.setHighValue(m.getHighValue());
        bean.setLowValue(m.getLowValue());
        bean.setLocation(m.getLocation());
        bean.setResponsibleDept(m.getResponsibleDept());
        String deptName = bpDepartDao.getNameById(Long.valueOf(m.getResponsibleDept()));
        bean.setResponsibleDeptName(deptName);
        bean.setRealtimeValue(mhMonitoringRealTimeService.getVauleByPointsUnits(m, bean.getRealtimeValue()));
        BpMonitoringPointRel rel = bpMonitoringPointRelDao.findByPointIdAndRefTypeNotEq(m.getId(), "manufacturing_tech");
        if (rel != null) {
            switch (rel.getRefType()) {
                case "production_facility":
                    Optional<BpProductionFacility> opf = bpProductionFacilityDao.findById(rel.getRefId());
                    if (opf.isPresent()) {
                        bean.setFacilityName(opf.get().getName());
                    }
                    break;
                case "store_tank_area":
                    Optional<BpStorageTankArea> oba = bpStorageTankAreaDao.findById(rel.getRefId());
                    if (oba.isPresent()) {
                        bean.setFacilityName(oba.get().getName());
                    }
                    break;
                case "store_tank":
                    Optional<BpStorageTank> obt = bpStorageTankDao.findById(rel.getRefId());
                    if (obt.isPresent()) {
                        bean.setFacilityName(obt.get().getName());
                    }
                    break;
                case "store_house":
                    Optional<BpStoreHouse> obh = bpStoreHouseDao.findById(rel.getRefId());
                    if (obh.isPresent()) {
                        bean.setFacilityName(obh.get().getName());
                    }
                    break;
            }
        }
        return bean;
    }

    @Override
    public MhMonitoringPointBean getById(Long id) {
        MhMonitoringPoint one = dao.getOne(id);
        MhMonitoringPointBean mhMonitoringPointBean = new MhMonitoringPointBean();
        mhMonitoringPointBean.setId(one.getId());
        mhMonitoringPointBean.setName(one.getName());
        mhMonitoringPointBean.setMinitoringTypeName(one.getMhMonitoringType().getName());
        mhMonitoringPointBean.setPointCode(one.getPointCode());
        mhMonitoringPointBean.setRealtimeValue(one.getRealtimeValue());
        mhMonitoringPointBean.setHighValue(one.getHighValue());
        mhMonitoringPointBean.setLowValue(one.getLowValue());
        mhMonitoringPointBean.setLocation(one.getLocation());
        mhMonitoringPointBean.setResponsibleDept(one.getResponsibleDept());
        return mhMonitoringPointBean;
    }

    @Override
    public List<MhMonitoringPointBean> findByIds(List<Long> ids) {
        List<MhMonitoringPointBean> beans=new ArrayList<>();
        List<MhMonitoringPoint> list = dao.findByIds(ids);
        for (MhMonitoringPoint one : list) {
            MhMonitoringPointBean mhMonitoringPointBean = new MhMonitoringPointBean();
            mhMonitoringPointBean.setId(one.getId());
            mhMonitoringPointBean.setName(one.getName());
            mhMonitoringPointBean.setMinitoringTypeName(one.getMhMonitoringType().getName());
            mhMonitoringPointBean.setPointCode(one.getPointCode());
            mhMonitoringPointBean.setRealtimeValue(one.getRealtimeValue());
            mhMonitoringPointBean.setHighValue(one.getHighValue());
            mhMonitoringPointBean.setLowValue(one.getLowValue());
            mhMonitoringPointBean.setLocation(one.getLocation());
            mhMonitoringPointBean.setResponsibleDept(one.getResponsibleDept());
            beans.add(mhMonitoringPointBean);
        }
        return beans;
    }

    @Override
    public BpMonitoringPointBean getByIds(Long id) {
        MhMonitoringPoint one = dao.getOne(id);
        BpMonitoringPointBean bpMonitoringPointBean = new BpMonitoringPointBean();
        bpMonitoringPointBean.setId(one.getId());
        bpMonitoringPointBean.setName(one.getName());
        bpMonitoringPointBean.setMinitoringTypeName(one.getMhMonitoringType().getName());
        bpMonitoringPointBean.setPointCode(one.getPointCode());
        bpMonitoringPointBean.setRealtimeValue(one.getRealtimeValue());
        if (one.getMhMonitoringType().getId() == 3) {
            bpMonitoringPointBean.setFloor(one.getHighValue2());
            bpMonitoringPointBean.setUpperLimit(one.getLowValue2());
        } else {
            bpMonitoringPointBean.setFloor(one.getLevel2Threshold());
            bpMonitoringPointBean.setUpperLimit(one.getLevel1Threshold());
        }
        bpMonitoringPointBean.setAction(one.getAlarmAction());
        return bpMonitoringPointBean;
    }

    @Override
    public Double realTimeVal(MhMonitoringPoint p) {
        Optional<MonitorPointData> monitorPointData = monitorPointDataService.realTimeVal(p.getTenentId(),
                p.getOrgCode(), p.getPointCode());
        return monitorPointData.map(MonitorPointData::getValue).orElse(null);
    }

    private Integer querySensorState(String pointCode) {
        return 0;
    }

    private MhMonitoringPointListBean convert(MhMonitoringPoint m) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<MhMonitoringPoint> findAll(Long tenantId, String orgCode) {
        return dao.findByTenentIdAndOrgCode(tenantId, orgCode);
    }

    @Override
    public List<MhMonitoringPoint> findAllHaveLocation() {
        return dao.findAllHaveLocation();
    }

    @Override
    public void batchSwitch(MhMonitoringPointReqBean bean) {
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(bean.getIds())) {
            dao.batchSwitch(bean.getState(),bean.getIds());
        }
    }

    @Override
    public String getKeyFromData(MhMonitoringPoint point) {
        // key sample: mh-monitoring-point:tenantId:orgCode:pointCode
        return String.format("mh-monitoring-point:%s:%s:%s", point.getTenentId(), point.getOrgCode(),
                point.getPointCode());
    }

    @Override
    public Long getDataVersion(String key) {
        // key sample: mh-monitoring-point:tenantId:orgCode:pointCode
        String[] split = key.split(":");
        String tenantId = split[1];
        String orgCode = split[2];
        String pointCode = split[3];
        MhMonitoringPoint point = dao.findByTenentIdAndOrgCodeAndPointCode(Long.parseLong(tenantId), orgCode,
                pointCode);
        return point == null ? null : point.getUpdateTime().toEpochSecond(ZoneOffset.of("+8"));
    }

    @Override
    public MhMonitoringPoint getFromRealDataSource(String key) {
        // key sample: mh-monitoring-point:tenantId:orgCode:pointCode
        String[] split = key.split(":");
        String tenantId = split[1];
        String orgCode = split[2];
        String pointCode = split[3];

        MhMonitoringPoint dbPoint = dao.findByTenentIdAndOrgCodeAndPointCode(Long.parseLong(tenantId), orgCode,
                pointCode);
        MhMonitoringPoint tmp = new MhMonitoringPoint();
        MhMonitoringType tmpType = new MhMonitoringType();
        if (dbPoint != null) {
            BeanUtils.copyProperties(dbPoint, tmp);
            if (dbPoint.getMhMonitoringType() != null) {
                BeanUtils.copyProperties(dbPoint.getMhMonitoringType(), tmpType);
                tmp.setMhMonitoringType(tmpType);
            }
        }
        return tmp;
    }

    @Override
    public List<MhMonitoringPoint> findBindedPointsByType(MhMonitoringType type) {
        if (type == null) {
            return Collections.EMPTY_LIST;
        }
        List<MhMonitoringPoint> points = dao.selectBindedPointsByType(type.getId());
        return points;
    }

    @Override
    public List<MhMonitoringPoint> findBindedPointsByTypeName(String typeName) {
        MhMonitoringType type = mhMonitoringTypeDao.findFirstByName(typeName);
        if (type == null) {
            return Collections.EMPTY_LIST;
        }
        return findBindedPointsByType(type);
    }

    @Override
    public BpDeviceFacilityCollection findMonitoringPointBindToDevice(Long pointId) {
        List<BpDeviceFacilityCollection> list = bpDeviceFacilityCollectionDao.queryMonitoringPointBindDevice(pointId);
        return list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public List<MhMonitoringPoint> findBindedPointsByTypeNameLike(String typeName) {
        List<MhMonitoringType> list = mhMonitoringTypeDao.findByNameContains(typeName);
        if (list.isEmpty()) {
            return Collections.EMPTY_LIST;
        } else {
            List<Long> collect = list.stream().map(MhMonitoringType::getId).collect(Collectors.toList());
            // return dao.selectBindedPointsByTypes(list);
            return dao.findAllair(collect);
        }

    }

    @Override
    public long countAll() {
        Long count = dao.findCount();
        if (count == null) {
            return 0;
        } else {
            return count;
        }
    }

    @Override
    public void changeState(Long id, int state) {
        dao.findById(id).ifPresent((e) -> {
            e.setState(state);
            dao.save(e);
            delete(getKeyFromData(e));
        });
    }

    @Override
    public ResultBean deleteById(Long id) {
        MhMonitoringPoint mhMonitoringPoint = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("操作失败"));
        MhMonitoringType type = mhMonitoringTypeDao.findById(mhMonitoringPoint.getMhMonitoringType().getId()).get();
        List<MhPlatformPoint> fpList = mhPlatformPointDao.findByPointId(id);
        if (!CollectionUtils.isEmpty(fpList)) {
            throw new IllegalArgumentException("请先删除平台对接下的监测点");
        }
        //清监测点缓存
        delete(getKeyFromData(mhMonitoringPoint));
        //删除设备设施工艺模块所有关联
        //生产装置
        bpMonitoringPointRelDao.deleteByMonitoringPointId(id);
        //删除生产装置的绑定
        bpDeviceFacilityMonitoringPointDao.deleteByMonitoringPointId(id);
        //删除报警信息
        handleAlarms(id);
        //删除监测点
        mhMonitoringPoint.setShowState(DataStateTypes.UN_EFFECTIVE.getState());
        dao.save(mhMonitoringPoint);
        changeTypeNumber(type);
        return ResultBean.defaultSuccessResult();
    }

    public void handleAlarms(Long pointId) {
        List<MhAlarmMessage> messages = mhAlarmMessageDao.findByMhPointIdAndStateNotEq(pointId);
        if (CollectionUtils.isEmpty(messages)) {
            return;
        }
        messages.forEach(e -> {
            e.setDeleteFlag("1");
        });
        monitoringCenterService.handlingHazardAlarms(messages);
        mhAlarmMessageDao.removeHandledMessagesByMonitoringPointId(pointId);
    }

    /**
     * 判断一个监测点只能绑定一个设备/仓库/储罐区/储罐/工艺流程
     * 仓库判断单独处理 BpStoreHouseServiceImpl-checkHousePoint
     *
     * @param mhPointId
     */
    @Override
    public String checkMhMointPoint(Long mhPointId, Long refId) {

        String str = "";
        Optional<MhMonitoringPoint> optionalMp = dao.findById(mhPointId);
        if (optionalMp.isPresent()) {
            MhMonitoringPoint mhMonitoringPoint = optionalMp.get();
            List<BpMonitoringPointRel> pointList = bpMonitoringPointRelDao.findByMonitoringPointIdAndRefId(mhPointId, refId);
            if (!CollectionUtils.isEmpty(pointList)) {
                for (BpMonitoringPointRel rel : pointList) {
                    switch (rel.getRefType()) {
                        case "production_facility":
                            Optional<BpProductionFacility> opf = bpProductionFacilityDao.findById(rel.getRefId());
                            if (opf.isPresent()) {
                                str = str + "设备装置" + "(" + opf.get().getCode() + ") ";
                            }
                            break;
                        case "store_tank_area":
                            Optional<BpStorageTankArea> oba = bpStorageTankAreaDao.findById(rel.getRefId());
                            if (oba.isPresent()) {
                                str = str + "储罐区" + "(" + oba.get().getCode() + ") ";
                            }
                            break;
                        case "store_tank":
                            Optional<BpStorageTank> obt = bpStorageTankDao.findById(rel.getRefId());
                            if (obt.isPresent()) {
                                str = str + "储罐" + "(" + obt.get().getUniCode() + ") ";
                            }
                            break;
                        case "store_house":
                            Optional<BpStoreHouse> obh = bpStoreHouseDao.findById(rel.getRefId());
                            if (obh.isPresent()) {
                                str = str + "仓库管理" + "(" + obh.get().getCode() + ") ";
                            }
                            break;
                    }
                }
            }
            if (StringUtils.isNotBlank(str)) {
                str = mhMonitoringPoint.getName() + "(" + mhMonitoringPoint.getPointCode() + ")已被 " + str + "关联";
            }
        }
        return str;
    }

    /**
     * 批量删除监测点
     *
     * @param ids
     */
    @Override
    public void deletePoints(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new IllegalArgumentException("请选择需要删除的监测点");
        }
        for (Long id : ids) {
            deleteById(id);
        }

    }

    @Override
    @EnableDataPermission
    public List<MhMonitoringPoint> findByResponsibleDept() {
        return dao.findAll();
    }
/*
    @Override
    public List<MhMonitoringPoint> findNoxiousGas() {
        return dao.findAllBytypeId(Long.valueOf(51));
    }

    @Override
    public List<MhMonitoringPoint> findInflammableAandExplosiveGas() {
        return dao.findAllBytypeId(Long.valueOf(52));
    }*/

    /**
     * 修改该类型下 监测点数量
     *
     * @param type
     */
    private void changeTypeNumber(MhMonitoringType type) {
        //更改监测点数量
        List<MhMonitoringPoint> pList = dao.findByMhMonitoringType(type.getId());
        if (pList != null && pList.size() > 0) {
            type.setNumber(pList.size());
        } else {
            type.setNumber(0);
        }
        mhMonitoringTypeDao.save(type);
    }


    @Override
    public MhMonitoringPointDto getMhMonitoringPointById(Long id) throws ApiBusinessException {
        MhMonitoringPoint point = dao.findFirstByIdAndState(id);
        if (null == point) {
            throw new ApiBusinessException(Status.MONITOR_POINT_NOT_FIND_ERROR);
        }
        MhMonitoringPointDto mhMonitoringPointDto = new MhMonitoringPointDto();
        BeanUtils.copyProperties(point, mhMonitoringPointDto);
        mhMonitoringPointDto.setMhMonitoringTypeName(point.getMhMonitoringType().getName());
        return mhMonitoringPointDto;
    }
}
